package com.gitee.huanminabc.utils_tools.file_tool.excel.easy;

import com.alibaba.excel.converters.Converter;
import com.alibaba.excel.metadata.GlobalConfiguration;
import com.alibaba.excel.metadata.data.ReadCellData;
import com.alibaba.excel.metadata.data.WriteCellData;
import com.alibaba.excel.metadata.property.ExcelContentProperty;
import com.gitee.huanminabc.jcommon.enums.EnumSuper;
import com.gitee.huanminabc.utils_tools.file_tool.annotation.EasyEnumMethod;
import lombok.extern.slf4j.Slf4j;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.text.ParseException;

/**
 * @program: monorepo
 * @description: 兼容Long转换String , 内置的不会兼容数字等类型转化为Long
 * @author: huanmin
 * @create: 2025-01-02 17:28
 **/
@Slf4j
public class EasyEnumSuperConverter implements Converter<EnumSuper> {
    @Override
    public EnumSuper convertToJavaData(ReadCellData<?> cellData, ExcelContentProperty contentProperty,
                                         GlobalConfiguration globalConfiguration) throws ParseException {
        //判断
        if (cellData.getStringValue() != null) {
            String method = "getEnumByDesc";
            Field field = contentProperty.getField();
            EasyEnumMethod annotation = field.getAnnotation(EasyEnumMethod.class);
            if (annotation != null) {
                method = annotation.value();
            }
            try {
                Class<?> declaringClass = field.getType();
                Method classMethod = declaringClass.getMethod(method, String.class);
                Object invoke = classMethod.invoke(declaringClass, cellData.getStringValue());
                //判断类型
                if (invoke instanceof EnumSuper) {
                    return (EnumSuper) invoke;
                }
                return null;
            } catch (Exception e) {
                log.error("EasyEnumAbilityConverter 枚举转换异常:", e);
            }
        }
        return null;
    }

    @Override
    public WriteCellData<?> convertToExcelData(EnumSuper value, ExcelContentProperty contentProperty,
                                               GlobalConfiguration globalConfiguration) {
        return new WriteCellData<String>(value.getDescription());
    }
}
